<?php

namespace app\admin\middleware;

use app\BaseController;
use app\service\admin\AdminRoleLogic;
use app\service\admin\RolePurviewLogic;
use think\facade\Session;

class CheckPrivilege extends BaseController
{
    /**
     * 白名单
     * @var string[]
     */
    protected $arrWhite = [
        '/admin/index/index',
        '/admin/login/index',
        '/admin/login/logout',
    ];

    /**
     * 处理请求
     * @param $request
     * @param $next
     * @return \think\response\Json
     */
    public function handle($request, $next)
    {
        $roleId = Session::get('role_id');
        $url = request()->baseUrl();
        $url = str_replace('.html', '',  $url);
        if ($roleId != AdminRoleLogic::SUPER) {
            // 白名单
            $hasPrivilege = RolePurviewLogic::getInstance()->check($url, $roleId);
            // 权限
            $isWrite = in_array($url, $this->arrWhite);
            if (!$hasPrivilege && !$isWrite) {
                return error('您没有权限');
            }
        }
        return $next($request);
    }
}